//
//  AELTrackControlController.swift
//  ActualExaminationLine
//
//  Created by iOS-Czz on 2023/10/30.
//

import UIKit
import WMZDialog

class AELTrackControlController: AELBaseViewController,UITextFieldDelegate {
    lazy var viewModel: AELTrackControlViewModel = {
        return AELTrackControlViewModel()
    }()
    lazy var weatherViewModel: AELWeatherViewModel = {
        return AELWeatherViewModel()
    }()
    @IBOutlet var reservationLabel: UILabel!
    var timer: Timer?
    
    @IBOutlet var dateLabel: UILabel!
    @IBOutlet var timeLabel: UILabel!
    @IBOutlet var bookingLabel: UILabel!
    @IBOutlet var pageTab: UITableView!
    
    @IBOutlet var weatherLabel: UILabel!
    @IBOutlet var weatherIcon: UIImageView!
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getPageData()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.wx_navigationBar.isHidden = true
        setTab()
        // 设置 Timer，每秒钟触发一次更新时间的方法
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
        timer?.fire() // 立即触发第一次更新时间
        // Do any additional setup after loading the view.
    }
    @objc func updateTime() {
        let currentDate = Date() // 获取当前时间
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm" // 设置时间格式
        
        let formattedDate = dateFormatter.string(from: currentDate) // 格式化当前时间为字符串
        
        // 在 UILabel 上显示当前时间
        timeLabel.text = formattedDate
        dateLabel.text = Date().toString(format: "yyyy.MM.dd")
    }
    
    deinit {
        timer?.invalidate() // 当不再需要时，停止 Timer
    }
    
    func getPageData(){
        self.viewModel.loadData( onSuccess: { models in
            if self.viewModel.resetvationCount < 10 {
                self.reservationLabel.text = String(format: "0%ld", self.viewModel.resetvationCount)
            }else{
                self.reservationLabel.text = String(format: "%ld", self.viewModel.resetvationCount)
            }
            if self.viewModel.bookingCount < 10 {
                self.bookingLabel.text = String(format: "0%ld", self.viewModel.bookingCount)
            }else{
                self.bookingLabel.text = String(format: "%ld", self.viewModel.bookingCount)
            }
            self.pageTab.reloadData()
        })
        self.weatherViewModel.loadData {[self] models in
            let model = models.first
            self.weatherIcon.image = UIImage(named: WEATHER_SMALL_ICONS[model!.weather])
            self.weatherLabel.text = WEATHERS[model!.weather]
        }
    }
    @IBAction func tapWeatherAction(_ sender: Any) {
        self.navigationController?.pushViewController(AELWeatherRecordController(), animated: true)
    }
    func setTab(){
        pageTab.dataSource = self
        pageTab.delegate = self
        pageTab.register(UINib(nibName: "AELTrackControlCell", bundle: .main), forCellReuseIdentifier: "AELTrackControlCell")
        
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        getPageData()
        self.view.endEditing(true)
        return true
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        getPageData()
        self.view.endEditing(true)
    }
    @IBAction func clickAddAction(_ sender: Any) {
        self.navigationController?.pushViewController(AELAddTrackControlController(), animated: true)
    }
}

extension AELTrackControlController:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.dataSource.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:AELTrackControlCell = tableView.dequeueReusableCell(withIdentifier: "AELTrackControlCell")  as! AELTrackControlCell
        cell.model = self.viewModel.dataSource[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    func addSub(){
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "")
        label.frame = CGRect(x: 205, y: 431.5, width: 52, height: 13)
        label.numberOfLines = 0
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont(name: "ssa", size: 13) as Any,.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        view.addSubview(label)
    }
}
